//
//  CNLoadingView.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2018/5/31.
//  Copyright © 2018年 CSDN. All rights reserved.
//

#import "CNLoadingGifView.h"
#import <CNBaseTool/CNCategoryHeader.h>

@implementation CNLoadingGifView

{
    YYAnimatedImageView *_loadingView;
}

- (id)initWithFrame:(CGRect)frame{
    
    if (self == [super initWithFrame:frame]) {
        
        self.theme_backgroundColor = pageBGColorPicker;
        [self configUI];
        //监听更换皮肤通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSkin) name:CNThemeUpdateNotification object:nil];
    }
    return self;
}


- (void)configUI{
    
    _loadingView = [[YYAnimatedImageView alloc] init];
    [self addSubview:_loadingView];
    [_loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(80, 80));
        make.center.mas_equalTo(0);
    }];
    
//    NSString *hdPath = [[NSBundle mainBundle] pathForResource:@"LoadingAnimation" ofType:@"gif"];
//    NSData *data = [NSData dataWithContentsOfFile:hdPath];
//    YYImage *image = [YYImage imageWithData:data];
//    _loadingView.image = image;
    
    NSMutableArray *animatedImages = [[NSMutableArray alloc] initWithCapacity:5];
    for (int i = 1; i < 5; i++) {
        if ([CNThemesManager isNight])
        {
            NSString *animatedImageName = [NSString stringWithFormat:@"lloding%d_b",i];
            UIImage *animatedImage = [UIImage imageNamed:animatedImageName];
            [animatedImages addObject:animatedImage];
        }
        else
        {
            NSString *animatedImageName = [NSString stringWithFormat:@"lloding%d_w",i];
            UIImage *animatedImage = [UIImage imageNamed:animatedImageName];
            [animatedImages addObject:animatedImage];
        }
        
    }
    
    _loadingView.animationImages = animatedImages;
    _loadingView.animationRepeatCount = MAXFLOAT;
    _loadingView.animationDuration = 0.7;
    [_loadingView startAnimating];
    
}

#pragma mark - 外部方法
- (void)dismissLoadingView{
    
    [UIView animateWithDuration:3.0f animations:^{
        self.alpha = 0.0f;
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
    
}

-(void)changeSkin
{
    [self configUI];
}

- (void)dealloc{
    
    if (_loadingView) {
        [_loadingView removeFromSuperview];
        _loadingView = nil;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
}

@end
